# YADT common bash functions

# source in YADT configuration
source /etc/default/yadt

# return a list of "our" packages
function yadt_our_packages {
	# recursively query requires, filtering out protected packages and non-package requires till no new "our" packages
	# come as a result
	
	# set some defaults
	YADT_OUT_PACKAGES_FILTER="${YADT_OUR_PACKAGES_FILTER:-.*}"
	YADT_PROTECTED_PACKAGES_FILTER="${YADT_PROTECTED_PACKAGES_FILTER:-yadt-client}"

	PACKAGES=( $(yadt_config_package) )
	OLDPACKAGES=()
	let c=0
	until [ "${PACKAGES[*]}" = "${OLDPACKAGES[*]}" ] ; do
		OLDPACKAGES=( "${PACKAGES[@]}" )
		PACKAGES=( $(rpm -q --requires --queryformat "%{NAME}\n" "${OLDPACKAGES[@]}" | \
				grep -v -E '(\/|\()' | \
				cut -d " " -f 1 | \
				grep -E "$YADT_OUR_PACKAGES_FILTER" | \
				sort -u ) 
			)
		#declare -p PACKAGES
		#let "c++>3" && return
	done
	unset OLDPACKAGES
	#echo 1>&2 "requirements walked down from config: 
#${PACKAGES[@]}"
	# now find out which packages provide that and filter out protected packages
	PACKAGES=( $( rpm -q --whatprovides --queryformat "%{NAME}\n" "${PACKAGES[@]}" | \
			grep -vE "$YADT_PROTECTED_PACKAGES_FILTER" | \
			sort -u )
		)
	#echo 1>&2 "packages providing that:
#${PACKAGES[@]}"
	# now make one last extra iteration, get their requirements and filter out the protected packages
	PACKAGES=( "${PACKAGES[@]}" $( rpm -q --requires --queryformat "%{NAME}\n" "${PACKAGES[@]}" | \
			grep -v -E '(\/|\()' | \
			cut -d " " -f 1 | \
			sort -u ) 
		)
	#echo 1>&2 "and their requirements:
#${PACKAGES[@]}"
	# and again find out which packages provide that and filter out the protected packages
	rpm -q --whatprovides --queryformat "%{NAME}\n" "${PACKAGES[@]}" "${PACKAGES2[@]}" | \
			grep -vE "$YADT_PROTECTED_PACKAGES_FILTER" | \
			sort -u
}

# return our config RPM {
function yadt_config_package {
	if [ -n "$YADT_CONFIG_PACKAGE" ] ; then
		rpm -q --whatprovides "$YADT_CONFIG_PACKAGE" --queryformat "%{NAME}"
		return $?
	else
		Error "Required Variable 'YADT_CONFIG_PACKAGE' not set in /etc/default/yadt" 
	fi
}

# log to stderr and syslog and abort
function Error {
	logger -s -t "$0" "$@"
	exit 1
}
